package edu.chl.jadetalk.control;

import edu.chl.jadetalk.business.UserManagerBeanLocal;
import edu.chl.jadetalk.view.LoginBackingBean;
import edu.chl.jadetalk.core.User;
import edu.chl.jadetalk.user.UserSessionBean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

/**
 *
 * @author jesper
 */
@ManagedBean
@RequestScoped
public class LoginControllerBean {

    @ManagedProperty(value = "#{loginBackingBean}")
    private LoginBackingBean loginBackingBean;
    
    @ManagedProperty(value = "#{userSessionBean}")
    private UserSessionBean userSessionBean;
    
    @EJB
    private UserManagerBeanLocal userManagerBean;

    public String login() {

        User user = userManagerBean.loginUser(loginBackingBean.getName(), loginBackingBean.getPassword());

        if (user != null) {
            userSessionBean.setUser(user);
            Logger.getAnonymousLogger().log(Level.OFF, "--Log in successful. User in session bean: {0}", userSessionBean.getUser().getUsername());
            loginBackingBean.setMessage("Logged in as " + userSessionBean.getUser().getUsername() + ".");
            return "onLogin";
        } else {
            Logger.getAnonymousLogger().log(Level.OFF, "--Log in failed.");
            loginBackingBean.setMessage("Incorrect username or password.");
            return "";
        }

    }

    public boolean isLoggedIn() {
        return userSessionBean.getUser() != null;
    }

    public UserManagerBeanLocal getUserManagerBean() {
        return userManagerBean;
    }

    public void setUserManagerBean(UserManagerBeanLocal userManagerBean) {
        this.userManagerBean = userManagerBean;
    }

    public LoginBackingBean getLoginBackingBean() {
        return loginBackingBean;
    }

    public void setLoginBackingBean(LoginBackingBean loginBackingBean) {
        this.loginBackingBean = loginBackingBean;
    }

    public UserSessionBean getUserSessionBean() {
        return userSessionBean;
    }

    public void setUserSessionBean(UserSessionBean userSessionBean) {
        this.userSessionBean = userSessionBean;
    }

    public String logout() {
		Logger.getAnonymousLogger().log(Level.OFF, "Pressed logout, the user is " + userSessionBean.getUser());
        userSessionBean.setUser(null);
        return "onLogout";
    }
}
